Skip to content

Teste roberta#1

Open
rob364 wants to merge 20 commits intowlsf82:mainfrom
rob364:Teste_Roberta
Open

Teste roberta#1
rob364 wants to merge 20 commits intowlsf82:mainfrom
rob364:Teste_Roberta

Conversation

@rob364
Copy link
Copy Markdown

@rob364 rob364 commented Mar 15, 2025

Foram feitas as alterações sugeridas pelo Walmyr!

✅ Descrição das alterações

Este PR adiciona uma bateria de testes automatizados para o projeto EngageSphere, cobrindo as camadas API e GUI com foco em confiabilidade e boas práticas de teste com Cypress.

🧪 Testes de API

Verifica o status 200 na recuperação de clientes.
Confirma que a API retorna 10 clientes por página.
Valida que a paginação retorna corretamente a currentPage.

🖥️ Testes de GUI

Verifica a saudação padrão e personalizada ("Hi there!" e "Hi Joe").
Garante a visibilidade e integridade do rodapé com todos os links.
Valida que filtros de tamanho e indústria são aplicados corretamente e mantidos ao navegar de volta.
Testa o botão "Back" na visualização de detalhes do cliente.

@wlsf82
Copy link
Copy Markdown
Owner

wlsf82 commented Mar 15, 2025

@rob364, antes mesmo de iniciar a revisão, recomendo escrever melhores mensagens de commit visto que estas ajudam o revisor do código entender cada mudança.

Por exemplo: a mensagem Adicionada nova funcionalidade X deveria ser algo como Install and configure Cypress, uma vez que é isso que tal commit faz.

Outro exemplo: a mensagem criação de data-test p table e incremento no testes de API dá a impressão de que mudanças foram feitas no frontend neste commit, quando na verdade tal commit somente fez alterações em arquivos de testes.

Por fim, a mensagem Ultimas alterações não trás significado algum.

Para aprender como escrever boas mensagens de commit, recomendo o seguinte conteúdo: How to Write a Git Commit Message.

Copy link
Copy Markdown
Owner

@wlsf82 wlsf82 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bom trabalho @rob364! 🎉

No entanto, deixei uma série de comentários ao longo do seu código, os quais creio que lhe ajudarão a melhorar bastante o design do mesmo.

Obs.: Só faça novas alterações depois do encontro de hoje da Test Design Masterclass.

Comment thread README.md Outdated
Comment thread README.md Outdated
Comment thread cypress/e2e/Testes/TestesApi.cy.js Outdated
@@ -0,0 +1,45 @@
describe("EngageSphere - Interface Inicial API", () => {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suítes de testes devem possuir descrições curtas e direto-ao-ponto.

Segue minha sugestão para a suíte de testes de API.

Suggested change
describe("EngageSphere - Interface Inicial API", () => {
describe("EngageSphere API", () => {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A propósito, por qual motivo você criou a pasta Testes/ dentro de cypress/e2e/ se a pasta e2e/ já é a pasta onde armazena-se os testes?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Além disso, o nome do arquivo de teste conter a palavra Teste é redundante visto que é óbvio que isso é uma suíte de testes.

Minha sugestão é que dentro da pasta cypress/e2e/ haja uma pasta chamada gui/ para os testes de interface gráfica de usuário e outra pasta chamada api/ para os testes de application programming interface.

No fim, a estrutura de arquivos de testes poderia ser assim:

  • cypress/e2e/gui/EngageSphere.cy.js para os testes de GUI da aplicação EngageSphere
  • cypress/e2e/api/EngageSphere.cy.js para os testes de API da aplicação EngageSphere

Comment thread cypress/e2e/Testes/TestesApi.cy.js Outdated

beforeEach(() => {
cy.visit("/");
cy.get('[data-test="accept-button"]').click();
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Em vez da adição do atributo data-test no botão de aceitar os cookies, você poderia simplesmente ter feito algo como o seguinte:

cy.contains('button', 'Accept').click()

Tal seletor é legível e não exigiria mudança no código do frontend.

Uma alternativa melhor ainda seria definir o cookie programaticamente.

Assim:

cy.setCookie('cookieConsent', 'accepted')

Dessa forma, não precisa-se perder tempo clicando no botão de aceitar cookies para testes onde isso é só uma pré-condição, não o alvo do teste.

Vale lembrar que o comando cy.setCookie deve ser executado antes do cy.visit.

Comment thread cypress/e2e/Testes/TestesApi.cy.js Outdated
@@ -0,0 +1,45 @@
describe("EngageSphere - Interface Inicial API", () => {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esta linha em branco só adiciona uma nova linha no código sem nenhum ganho real.

Por que tal prática fere um bom design de testes?

Em vez de ajudar na legibilidade do código, tal prática piora a mesma, visto que torna os
arquivos maiores do que o necessário.

Sugestão com um melhor design

Não deixe linhas em branco no início do arquivo, nem mais de uma linha entre diferentes
“coisas” (ex.: blocos it, beforeEach, context, etc.). Uma linha em branco (abaixo) já é o suficiente
para deixar a suíte de testes legível.

Veja um exemplo.

describe('EngageSphere', () => {
  beforeEach(() => {
    cy.visit('/')
  })

  it('shows the default greeting (i.e., Hi, there...)', () => {
    // Test implementation here
  })

  it('shows the customized greeting (i.e., Hi, Joe...)', () => {
    // Test implementation here
  })

  // Outros casos de teste aqui...
})

Comment thread frontend/src/components/Table/index.js Outdated
@@ -1,3 +1,90 @@
// import { useState } from 'react'
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Por qual motivo você comentou esse monte de código?

Comment thread frontend/src/components/Table/index.js Outdated
<th scope="col">ID</th>
<th scope="col">Company name</th>
<th scope="col">Industry</th>
<th scope="col" onClick={sortNumberOfEmployeesHandler} data-test="sort-employees-header">
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Você adicinou vários atributos data-test que nem mesmo estão em uso.

Código não utilizado é complexidade adicional.

Um bom design de código é um código que remove complexidade, não que adiciona.

Comment thread frontend/src/components/Table/index.js Outdated
aria-label={`View company: ${customer.name}`}
key={customer.id}
onClick={() => customerActionClickHandler(customer)}
data-test={`view-customer-${index}`}
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Em vez desse atributo data-test, o comando cy.contains('button', 'View') já resolveria o problema sem a necessidade de alteração no código do frontend.

Comment thread package.json Outdated
"start:frontend": "cd frontend && npm start",
"start:server": "cd backend && npm start"
"start:server": "cd backend && npm start",
"test:e2e": "start-server-and-test \"npm run start:server\" 3001 \"npm run start:frontend\" 3000 \"npx cypress open\""
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esse comando não funciona visto que faltou instalar a biblioteca start-server-and-test como uma dependência de desenvolvimento, ou seja, não está listada nas devDependencies.

Comment thread package.json Outdated
"devDependencies": {
"@babel/plugin-proposal-private-property-in-object": "^7.21.11"
"@babel/plugin-proposal-private-property-in-object": "^7.21.11",
"cypress": "^14.1.0"
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Que tal fazer o upgrade para a versão 14.2.0, lançada no dia 12/03/2025?

Fonte: https://docs.cypress.io/app/references/changelog#14-2-0

@rob364
Copy link
Copy Markdown
Author

rob364 commented Mar 21, 2025

Foram feitas as alterações sugeridas pelo Walmyr!

Descrição das alterações

Este PR adiciona uma bateria de testes automatizados para o projeto EngageSphere, cobrindo as camadas API e GUI com foco em confiabilidade e boas práticas de teste com Cypress.

🧪 Testes de API

Verifica o status 200 na recuperação de clientes.
Confirma que a API retorna 10 clientes por página.
Valida que a paginação retorna corretamente a currentPage.

🖥️ Testes de GUI

Verifica a saudação padrão e personalizada ("Hi there!" e "Hi Joe").
Garante a visibilidade e integridade do rodapé com todos os links.
Valida que filtros de tamanho e indústria são aplicados corretamente e mantidos ao navegar de volta.
Testa o botão "Back" na visualização de detalhes do cliente.

Copy link
Copy Markdown
Owner

@wlsf82 wlsf82 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bom trabalho@rob364! 👏🏻 👏🏻

No entanto, deixei mais comentários os quais creio que lhe ajudarão a melhorar o design dos testes.

Lembre-se se só fazer novas alterações após o terceiro encontro da Test Design Masterclass da TAT.

Comment thread .gitignore
Comment thread .gitignore

# misc
.DS_Store
cypress/fixtures/
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As pastas cypress/fixtures/ e cypress/support/ não devem ser listadas no arquivo .gitignore.

Em vez disso, se você não vai as utilizar, deve atualizar o arquivo de configurações com as opções fixtureFolder: fase e supportFile: false, deletá-las e mais nada.

Comment thread .gitignore
Comment thread .gitignore
.DS_Store
cypress/fixtures/
/Lixo
/bash.exe.stackdump
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

E esse arquivo?

Comment thread .gitignore
Comment thread cypress/support/e2e.js
@@ -0,0 +1 @@
import './commands' No newline at end of file
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Faltou deletar este arquivo também.

</div>
)}
<Button text="Back" onClick={onClick} />
<Button text="Back" onClick={onClick} datatest="button-back" />
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esse datatest não é necessário, visto que é possível selecionar o botão com o comando cy.contains('button', 'Back').

<td>{customer.employees}</td>
<td>{customer.size}</td>
<td onClick={() => customerActionClickHandler(customer)}>
<td onClick={() => customerActionClickHandler(customer)} >
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Qual o motivo dessa mudança?

<td onClick={() => customerActionClickHandler(customer)} >
<strong>
<button aria-label={`View company: ${customer.name}`} key={customer.id} onClick={() => customerActionClickHandler(customer)}>
<button aria-label={`View company: ${customer.name}`} key={customer.id} onClick={() => customerActionClickHandler(customer)} >
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

E dessa?




// import { useState } from 'react'
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

E esse monte de código do frontend comentado?

Copy link
Copy Markdown

@brunonf15 brunonf15 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bom trabalho Roberta! Segue umas sugestões

Comment thread .gitignore
Comment thread README.md
}

export default Table

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remover esses códigos comentados

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants